import { getSysMenuCurrTree } from '@/api/management/user'
import constSrc from '@/router/routePermission'
import Layout from '@/layout'
// 导入静态路由表和全部的动态路由数组
import { constantRoutes } from '@/router'
const getDefaultState = () => {
  return {
    // 用来保存最终的路由表
    // 包含静态 + 静态，但是默认只有静态
    routes: [...constantRoutes]
  }
}

const state = getDefaultState()

// mutations
const mutations = {
  // 第二个参数就是传递过来的筛选后的动态路由
  setRoutes (state, routes) {
    // 最终路由有 静态 + 筛选后的动态
    state.routes = [...constantRoutes, ...routes]
  }
}

// actions
const actions = {
  // 把动态路由 和 静态路由合并生成菜单
  getRoutes (ctx, menus) {
    // 根据权限名过滤出动态数组里的路由
    const routes = menus
    ctx.commit('setRoutes', routes)
    return routes
  },
  // 获取后端返回的路由
  GenerateRoutes (ctx, code) {
    return new Promise(resolve => {
      // 向后端请求路由数据
      getSysMenuCurrTree(code).then(res => {
        let r = arrayToTree(JSON.parse(JSON.stringify(res.data.bdata)), '')
        isChildren(r)
        // 只有二级的路由作为addRouter
        let pj = arrayToTree(JSON.parse(JSON.stringify(res.data.bdata)), '')
        isChildren(pj)
        towLevel(pj)
        pj.push({ path: '*', redirect: '/404', hidden: true })
        ctx.commit('setRoutes', r)
        resolve(pj)
      })
    })
  }
}

// 根据后端数据生成路由结构
function arrayToTree (arr, pid) {
  const list = []
  arr.forEach(v => {
    if (v.pid === pid) {
      let obj = {}
      obj.path = v.ab.addressCode
      if (v.pid == '' && constSrc.includes(v.ab.addressCode)) {
        obj.component = Layout
      } else {
        if (constSrc.includes(v.ab.addressCode)) {
          let component = `${v.ab.address}`
          obj.component = resolve =>
            require(['@/' + component + '.vue'], resolve)
        } else {
          obj.component = () => import('@/views/404')
        }
      }
      if (v.ab.addressCode.includes('/')) {
        obj.name = v.ab.addressCode.substr(1)
      } else {
        obj.name = v.ab.addressCode
      }
      obj.meta = {}
      obj.meta.title = v.name
      obj.meta.icon = v.icon
      // obj.alwaysShow = true
      list.push(obj)
      const children = arrayToTree(arr, v.id)
      if (children.length) obj.children = children
    }
  })
  return list
}

// 根据路由结构是否添加对应信息
function isChildren (arr) {
  arr.forEach(item => {
    if (item.children) {
      item.alwaysShow = true
      isChildren(item.children)
    }
  })
}

// 把完整路由结构 变成最多二级 的路由结构
function towLevel (arr) {
  arr.forEach(item => {
    if (item.children) {
      item.children = castToFlatRoute(item.children, '')
    }
  })
}

/**
 * 将子路由转换为扁平化路由数组（仅一级）
 * @param {待转换的子路由数组} routes
 * @param {父级路由路径} parentPath
 */
function castToFlatRoute (routes, parentPath, flatRoutes = []) {
  for (const item of routes) {
    if (item.children && item.children.length > 0) {
      if (item.redirect && item.redirect !== 'noRedirect') {
        flatRoutes.push({
          name: item.name,
          path: (parentPath + '/' + item.path).substring(1),
          redirect: item.redirect,
          meta: item.meta
        })
      }
      castToFlatRoute(item.children, parentPath + '/' + item.path, flatRoutes)
    } else {
      flatRoutes.push({
        name: item.name,
        path: (parentPath + '/' + item.path).substring(1),
        component: item.component,
        meta: item.meta
      })
    }
  }

  return flatRoutes
}

export default {
  namespaced: true,

  state,
  mutations,
  actions
}
